<template>
    <n-dropdown :options="options" @select="handleDropdown">
        <hover-container class="px-12px" :inverted="theme.header.inverted">
            <n-avatar round size="small" :src="auth.userInfo?.avatar" color="white" />
            <span class="pl-8px text-16px font-medium">{{
                auth.userInfo?.username
            }}</span>
        </hover-container>
    </n-dropdown>

    <jb-btn
        style="display: none"
        tip-text="重置密码"
        secondary
        icon="solar:lock-password-bold"
        circle
        type="warning"
        :modal-component="ResetPwd"
        modal-title="重置密码"
        modal-width="600px"
        ref="resetRef"
        @modal-yes-click="handleReset"
    >
    </jb-btn>
    <jb-btn
        style="display: none"
        tip-text="用户中心"
        secondary
        icon="solar:lock-password-bold"
        circle
        type="warning"
        :modal-component="UserEdit"
        modal-title="用户中心"
        modal-width="800px"
        ref="userRef"
        @modal-yes-click="handleResetUserInfo"
    >
    </jb-btn>
</template>

<script lang="ts" setup>
import type { DropdownOption } from 'naive-ui'
import { useAuthStore, useThemeStore } from '@/store'
import { useIconRender } from '@/composables'
import ResetPwd from "./reset-pwd/index.vue";
import UserEdit from "./user-edit/index.vue";
import {ref} from "vue";


defineOptions({ name: 'UserAvatar' })

const resetRef = ref(null)
const userRef = ref(null)

const auth = useAuthStore()
const theme = useThemeStore()
const { iconRender } = useIconRender()

const options: DropdownOption[] = [
    {
        label: '用户中心',
        key: 'user-center',
        icon: iconRender({ icon: 'carbon:user-avatar' })
    },
    {
        type: 'divider',
        key: 'divider'
    },
    {
        label: '重置密码',
        key: 'resetPwd',
        icon: iconRender({ icon: 'solar:lock-password-bold' })
    },
    {
        type: 'divider',
        key: 'divider'
    },
    {
        label: '退出登录',
        key: 'logout',
        icon: iconRender({ icon: 'carbon:logout' })
    }
]

type DropdownKey = 'resetPwd' | 'logout' | 'user-center'

function handleDropdown(optionKey: string) {
    const key = optionKey as DropdownKey
    if (key === 'logout') {
        window.$dialog?.info({
            title: '提示',
            content: '您确定要退出登录吗？',
            positiveText: '确定',
            negativeText: '取消',
            onPositiveClick: () => {
                auth.resetAuthStore()
            }
        })
    }else if(key==='resetPwd'){
        resetRef?.value.showModal()
    }else if(key==='user-center'){
        userRef?.value.showModal()
    }
}

function handleReset({close,componentRef}){
    componentRef.submit().then(()=>{
        close()
    })
}

function handleResetUserInfo({close,componentRef}){
    componentRef.submit().then(()=>{
        close()
        useAuthStore().refreshUserInfo()
    })

}
</script>

<style scoped></style>
